
package org.linlinjava.litemall.wx.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.checkerframework.checker.units.qual.A;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.LpUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import static org.linlinjava.litemall.wx.util.WxResponseCode.AUTH_CAPTCHA_UNMATCH;
import static org.linlinjava.litemall.wx.util.WxResponseCode.INSUFFICIENT_BALANCE;


/**
* <p>说明： 用户钱包表API接口层</P>
* @version: V1.0
* @author: wlx
* @time    2021年02月19日
*
*/
@Api(value = "商品管理",tags="商品管理" )
@RestController
@RequestMapping("/wx/goodsV2")
public class GoodsController {


	@Autowired
	LpGoodsService goodsService;

	@Autowired
	ConsumeRecordService consumeRecordService;

	@Autowired
	ClientConfigService  clientConfigService;

	@Autowired
	CustAccountbaseService custAccountbaseService;

	@Autowired
	UserGoodsService userGoodsService;

	@Autowired
	LpMarketService marketService;

	@Autowired
	LpGoodsBlindboxService goodsBlindboxService;

	@Autowired
	LpBlindboxService blindboxService;

	@Autowired
	LitemallBlindboxCategoryService litemallBlindboxCategoryService;

	@PostMapping("/collectionlist")
	@ApiOperation(value = "藏品出售列表", notes = "藏品出售列表")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object collectionlist(@LoginUser Integer userId, @RequestBody String body){

		Integer pageNum = JacksonUtil.parseInteger(body, "pageNum");
		Integer pageSize = JacksonUtil.parseInteger(body, "pageSize");
		Integer type = JacksonUtil.parseInteger(body, "type");





		PageHelper.startPage(pageNum,pageSize);
//		List<LpGoods> list = goodsService.list(null);
		QueryWrapper<LpMarket> wrapper = new QueryWrapper();
		wrapper.eq("type",type);
		List<LpMarket> list = marketService.list(wrapper);

		for (LpMarket lpMarket:list
			 ) {
			switch (lpMarket.getType()){
				case 1:
					lpMarket.setLpGoods(goodsService.getById(lpMarket.getGoodsId()));
					break;

				case 2:
					lpMarket.setLpGoodsBlindbox(goodsBlindboxService.getById(lpMarket.getGoodsId()));
					break;
			}
		}
		PageInfo<LpMarket> of = PageInfo.of(list);
		return ResponseUtil.ok(of);
	}


	@PostMapping("/collectioninfo")
	@ApiOperation(value = "藏品列表", notes = "藏品列表")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object collectioninfo(@LoginUser Integer userId, @RequestBody String body){

		Integer id = JacksonUtil.parseInteger(body, "id");

		return ResponseUtil.ok(goodsService.getById(id));
	}

	@Transactional
	@PostMapping("/buyCollection")
	@ApiOperation(value = "购买藏品", notes = "购买藏品")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object buyCollection(@LoginUser Integer userId, @RequestBody String body){

		Integer id = JacksonUtil.parseInteger(body, "id");
//		LpGoods goods = goodsService.getById(id);

		LpMarket market = marketService.getById(id);


		//查询自己的钱包余额 减少余额
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		CustAccountbase custAccountbase = custAccountbaseService.getOne(wrapper);

		if (market.getUserId() == userId){
			return ResponseUtil.fail(400, "该藏品属于您自己的");
		}


		if (market.getMoney() > custAccountbase.getAmount()){
			return ResponseUtil.fail(INSUFFICIENT_BALANCE, "余额不足");
		}




		custAccountbase.setAmount(custAccountbase.getAmount() - market.getMoney());

		custAccountbaseService.updateById(custAccountbase);

		//查询卖家的钱包余额 增加卖家余额
		QueryWrapper wrapper2 = new QueryWrapper();
		wrapper2.eq("user_id",market.getUserId());
		CustAccountbase custAccountbase2 = custAccountbaseService.getOne(wrapper2);


		custAccountbase2.setAmount(custAccountbase2.getAmount() + market.getActualMoney());
		custAccountbaseService.updateById(custAccountbase2);





		JSONObject jsonObject = clientConfigService.configToMap();



		LocalDateTime time = LocalDateTime.now();
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		String format = dateTimeFormatter.format(time);
		String numbers = RandomStringUtils.randomNumeric(5);
		String liushui = format+numbers;


		ConsumeRecord consumeRecord = new ConsumeRecord();
		consumeRecord.setUserId(market.getUserId().longValue());
		consumeRecord.setType(5);
		consumeRecord.setTradeNo(liushui);
		consumeRecord.setMoney( market.getActualMoney());
		consumeRecord.setChangeType(1);
		consumeRecord.setPayType(3);
		consumeRecord.setStatus(2);
		consumeRecord.setTime(new Date());
		consumeRecord.setToUserId(userId.longValue());
		consumeRecord.setDescs("出售藏品");
		consumeRecord.setCopyrightFee(market.getCopyrightFee());
		consumeRecord.setPayProcessingFees(market.getPayProcessingFees());
		consumeRecord.setPlatformFee(market.getPlatformFee());
		consumeRecord.setOperationAmount(market.getMoney());
		consumeRecordService.save(consumeRecord);



		ConsumeRecord consumeRecord2 = new ConsumeRecord();
		consumeRecord2.setUserId(userId.longValue());
		consumeRecord2.setType(4);
		consumeRecord2.setTradeNo(liushui);
		consumeRecord2.setMoney(market.getMoney());
		consumeRecord2.setChangeType(2);
		consumeRecord2.setPayType(3);
		consumeRecord2.setStatus(2);
		consumeRecord2.setTime(new Date());
		consumeRecord2.setToUserId(market.getUserId().longValue());
		consumeRecord2.setDescs("购买藏品");
		consumeRecord2.setOperationAmount(market.getMoney());
		consumeRecordService.save(consumeRecord2);


//		增加自己的藏品数量

		//查询是否拥有该藏品
		QueryWrapper wrapper1 = new QueryWrapper();
		wrapper1.eq("user_id",userId);
		wrapper1.eq("goods_id",market.getGoodsId());
		wrapper1.eq("type",1);
		UserGoods userGoodsServiceOne = userGoodsService.getOne(wrapper1);

		if (ObjectUtils.isEmpty(userGoodsServiceOne)){

			userGoodsServiceOne = new UserGoods();
			userGoodsServiceOne.setUserId(userId);
			userGoodsServiceOne.setGoodsId(market.getGoodsId());
			userGoodsServiceOne.setType(1);
			userGoodsServiceOne.setCount(1);
			userGoodsService.save(userGoodsServiceOne);


		}else {

			userGoodsServiceOne.setCount(userGoodsServiceOne.getCount() +1);
			userGoodsService.updateById(userGoodsServiceOne);


		}

		//删除市场上的藏品
		marketService.removeById(id);



		return ResponseUtil.ok();
	}

	@PostMapping("/saleCollection")
	@ApiOperation(value = "出售藏品", notes = "出售藏品")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object saleCollection(@LoginUser Integer userId, @RequestBody String body){
		Integer id = JacksonUtil.parseInteger(body, "id");
		String money = JacksonUtil.parseString(body, "money");


//		先查询自己有没有该藏品

		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		wrapper.eq("goods_id",id);
		wrapper.eq("type",1);
		UserGoods userGoodsServiceOne = userGoodsService.getOne(wrapper);

		if (ObjectUtils.isEmpty(userGoodsServiceOne)){
			return ResponseUtil.fail(-1,"藏品不存在");
		}


//		LpGoods goods = goodsService.getById(id);
		JSONObject jsonObject = clientConfigService.configToMap();
		Double copyrightFee = jsonObject.getDouble("copyrightFee");
		Double payProcessingFees = jsonObject.getDouble("payProcessingFees");
		Double platformFee = jsonObject.getDouble("platformFee");
		Double aDouble = Double.valueOf(money);

//		* copyrightFee	版权费
//     	* payProcessingFees	支付手续费
//     	* platformFee	平台手续费
//		map.get()
		double v = aDouble * (1D - copyrightFee - payProcessingFees - platformFee);
		LpMarket lpMarket = new LpMarket();

		lpMarket.setType(1);


		lpMarket.setCopyrightFee(aDouble * copyrightFee);
		lpMarket.setPayProcessingFees(aDouble * payProcessingFees);
		lpMarket.setPlatformFee(aDouble * platformFee);
		lpMarket.setUserId(userId);
		lpMarket.setGoodsId(id);

		marketService.save(lpMarket);

		userGoodsServiceOne.setCount(userGoodsServiceOne.getCount() -1);
		userGoodsService.updateById(userGoodsServiceOne);


		return ResponseUtil.ok();
	}
	@PostMapping("/cancelTheSaleCollection")
	@ApiOperation(value = "取消出售藏品", notes = "取消出售藏品")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object cancelTheSaleCollection(@LoginUser Integer userId, @RequestBody String body){
		Integer id = JacksonUtil.parseInteger(body, "id");
		String money = JacksonUtil.parseString(body, "money");

		return ResponseUtil.ok(goodsService.getById(id));
	}

//
//	@PostMapping("/myCollection")
//	@ApiOperation(value = "我的藏品", notes = "我的藏品")
//	@ApiImplicitParams({
//			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
//	})
//	public Object myCollection(@LoginUser Integer userId){
//
//		goodsService.
//		return ResponseUtil.ok();
//	}
	@PostMapping("/myCollection")
	@ApiOperation(value = "我的藏品", notes = "我的藏品")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object myCollection(@LoginUser Integer userId, @RequestBody String body){

		Integer pageNum = JacksonUtil.parseInteger(body, "pageNum");
		Integer pageSize = JacksonUtil.parseInteger(body, "pageSize");



		QueryWrapper<UserGoods> wrapper =new QueryWrapper();
		wrapper.eq("user_id",userId);
		PageHelper.startPage(pageNum,pageSize);
		List<UserGoods> userGoodsList = userGoodsService.list(wrapper);

		for (UserGoods userGoods:userGoodsList
			 ) {

			switch (userGoods.getType()){
				case 1:

					userGoods.setGoods(goodsService.getById(userGoods.getGoodsId()));
					break;
				case 2:
					userGoods.setLpBlindbox(blindboxService.getById(userGoods.getGoodsId()));
					break;
			}

		}
		PageInfo<UserGoods> of = PageInfo.of(userGoodsList);
		return ResponseUtil.ok(of);
	}



	@PostMapping("/listOfBlindBoxes")
	@ApiOperation(value = "盲盒列表", notes = "盲盒列表")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "Integer", name = "userId",value = "用户id",required = true),
	})
	public Object listOfBlindBoxes(@LoginUser Integer userId, @RequestBody String body) {
		Integer pageNum = JacksonUtil.parseInteger(body, "pageNum");
		Integer pageSize = JacksonUtil.parseInteger(body, "pageSize");
		Integer categoryId = JacksonUtil.parseInteger(body, "categoryId");
		PageHelper.startPage(pageNum,pageSize);
		QueryWrapper<LpBlindbox> wrapper = new QueryWrapper();
		wrapper.eq("is_on_sale",1);
		if (categoryId !=null && categoryId != 0){
			wrapper.eq("category_id",categoryId);
		}

		List<LpBlindbox> list = blindboxService.list(wrapper);
		for (LpBlindbox blindbox: list
			 ) {
			QueryWrapper w = new QueryWrapper();
			w.eq("category_id",blindbox.getId());
			blindbox.setLpGoods(goodsService.list(w));
		}
		PageInfo<LpBlindbox> of = PageInfo.of(list);
		return ResponseUtil.ok(of);
	}





	@Transactional
	@PostMapping("/buyBlindBox")
	@ApiOperation(value = "购买盲盒", notes = "购买盲盒")
	public Object buyBlindBox(@LoginUser Integer userId, @RequestBody String body) {
		Integer blindboxId = JacksonUtil.parseInteger(body, "blindboxId");

		LpBlindbox LpBlindbox = blindboxService.getById(blindboxId);

		if (LpBlindbox.getCount() <1){
			return ResponseUtil.fail(400,"库存不足");
		}

		CustAccountbase custAccountbase = custAccountbaseService.getCustAccountbase(userId);
		if (custAccountbase.getAmount()< LpBlindbox.getCounterPrice().doubleValue()){
			return ResponseUtil.fail(400,"余额不足");
		}

		custAccountbase.setAmount(custAccountbase.getAmount() -LpBlindbox.getCounterPrice().doubleValue());
		custAccountbaseService.updateById(custAccountbase);

		LpBlindbox.setCount(LpBlindbox.getCount() -1);
		blindboxService.updateById(LpBlindbox);
//		减去盲盒数量


		ConsumeRecord consumeRecord2 = new ConsumeRecord();
		consumeRecord2.setUserId(userId.longValue());
		consumeRecord2.setType(4);
		consumeRecord2.setTradeNo(LpUtils.generateOrderNumber());
		consumeRecord2.setMoney(LpBlindbox.getCounterPrice().doubleValue());
		consumeRecord2.setChangeType(2);
		consumeRecord2.setPayType(3);
		consumeRecord2.setStatus(2);
		consumeRecord2.setTime(new Date());
		consumeRecord2.setToUserId(0L);
		consumeRecord2.setDescs("购买盲盒");
		consumeRecord2.setOperationAmount(custAccountbase.getAmount());
		consumeRecordService.save(consumeRecord2);

		//查询是否拥有该盲盒
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("user_id",userId);
		wrapper.eq("goods_id",LpBlindbox.getId());
		wrapper.eq("type",2);
		UserGoods userGoodsServiceOne = userGoodsService.getOne(wrapper);

		if (ObjectUtils.isEmpty(userGoodsServiceOne)){

			userGoodsServiceOne = new UserGoods();
			userGoodsServiceOne.setUserId(userId);
			userGoodsServiceOne.setGoodsId(LpBlindbox.getId());
			userGoodsServiceOne.setType(2);
			userGoodsServiceOne.setCount(1);
			userGoodsService.save(userGoodsServiceOne);


		}else {



			userGoodsServiceOne.setCount(userGoodsServiceOne.getCount() +1);
			userGoodsService.updateById(userGoodsServiceOne);


		}




		return ResponseUtil.ok("购买成功");
	}

	@PostMapping("/openTheBlindBox")
	@ApiOperation(value = "打开盲盒", notes = "打开盲盒")

	public Object openTheBlindBox(@LoginUser Integer userId, @RequestBody String body) {

		Integer id = JacksonUtil.parseInteger(body, "id");
		UserGoods userGoods = userGoodsService.getById(id);



		if (ObjectUtils.isEmpty(userGoods) || userGoods.getCount() < 1 ){
			return ResponseUtil.fail(400,"盲盒不足");
		}


		QueryWrapper<LpGoodsBlindbox> wrapper = new QueryWrapper();
		wrapper.eq("blindbox_id",userGoods.getGoodsId());
		wrapper.orderByDesc("count");
		List<LpGoodsBlindbox> list = goodsBlindboxService.list(wrapper);

		int total = 0;
		for (LpGoodsBlindbox lpGoodsBlindbox:list
			 ) {
			total  += lpGoodsBlindbox.getCount();
		}


		Random random = new Random();
		int nextInt = random.nextInt(total);

		int total2 = 0;
		Integer goodsBlindboxId = null;
		for (LpGoodsBlindbox lpGoodsBlindbox:list
		) {

			total2  += lpGoodsBlindbox.getCount();
			if ( total2 > nextInt){
				if (goodsBlindboxId == null){
					goodsBlindboxId = lpGoodsBlindbox.getId();

					lpGoodsBlindbox.setCount(lpGoodsBlindbox.getCount() - 1);
					goodsBlindboxService.updateById(lpGoodsBlindbox);

					//减去用户盲盒数量
					if (userGoods.getCount() == 1){
						userGoodsService.removeById(userGoods.getId());
					}else {

						userGoods.setCount(userGoods.getCount() - 1);
						userGoodsService.updateById(userGoods);
					}



					//增加用户的藏品
					QueryWrapper w = new QueryWrapper();
					w.eq("user_id",userId);
					w.eq("goods_id",lpGoodsBlindbox.getGoodsId());
					w.eq("type",1);
					UserGoods userGoodsServiceOne = userGoodsService.getOne(w);

					if (ObjectUtils.isEmpty(userGoodsServiceOne)){

						userGoodsServiceOne = new UserGoods();
						userGoodsServiceOne.setUserId(userId);
						userGoodsServiceOne.setGoodsId(lpGoodsBlindbox.getGoodsId());
						userGoodsServiceOne.setType(1);
						userGoodsServiceOne.setCount(1);
						userGoodsService.save(userGoodsServiceOne);


					}else {

						userGoodsServiceOne.setCount(userGoodsServiceOne.getCount() +1);
						userGoodsService.updateById(userGoodsServiceOne);


					}

				}
			}

		}

//		计算概率  因为不是概率获取的 组合起来的盲盒需要计算概率

		userGoods.getGoodsId();

		return ResponseUtil.ok();
	}

	@PostMapping("/syntheticCollection")
	@ApiOperation(value = "合成藏品", notes = "合成藏品")
	public Object syntheticCollection(@LoginUser Integer userId, @RequestBody String body) {



		return ResponseUtil.ok();
	}


	@PostMapping("/blindBoxClassification")
	@ApiOperation(value = "合成藏品", notes = "合成藏品")
	public Object blindBoxClassification() {

		List<LitemallBlindboxCategory> list = litemallBlindboxCategoryService.list(null);


		return ResponseUtil.ok(list);
	}




}
